<script setup>
import { getStatusInfo } from '@u/ststus-color'
import {
  computed,
  getCurrentInstance,
  inject,
  nextTick,
  onMounted,
  ref,
  watch,
} from 'vue'
import {
  getRegionDetail,
  getResidenceTree,
  queryArea,
  queryQuestion,
  queryStatus,
} from '@api/question'
import { getColumns, getSpecialColumns } from '@u/download/getDownloadInfo'
import { cloneDeep } from 'lodash'
import emitter from '@/utils/event-bus'
import { PERMISSIONS } from '@/common/user'
import { Message } from 'element-ui'
import BuildEditPopup from '@/views/one-map/left-community-info/build-edit-popup.vue'
import { getBuildingInfo, getPoint, queryByResidenceId } from '@/api/building'
import { getBuildDetail } from '@/views/one-map/left-community-info/build-detail'

const vm = getCurrentInstance()

const user = JSON.parse(localStorage.getItem('user')).user

const { currentUser } = vm?.proxy.$store.state.user

const props = defineProps({
  detailInfo: {
    type: Object,
    default: () => {},
  },
  show: {
    type: Boolean,
    default: false,
  },
  status: {
    type: [Number, String],
    default: '',
  },
})

const getArea = () => {
  queryArea({}).then((res) => {
    if (res.success) {
      areaInfoList.value = res.data
    }
  })
}

const areaInfoList = ref([])

const colon = ref(true)

const refs = ref(null)

const emits = defineEmits(['update:pkid', 'applyRecord', 'closeDialog'])

const closeDialog = () => {
  emits('closeDialog')
}

const getParamsById = (id) => {
  const detailInfo = props.detailInfo
  let res
  if (detailInfo.type.includes('community')) {
    res = {
      communityId: id,
      templateType: 'community',
    }
  } else if (detailInfo.type.includes('street')) {
    res = {
      streetId: id,
      templateType: 'street',
    }
  } else if (detailInfo.type.includes('region-')) {
    res = {
      businessId: id,
      templateType: detailInfo.type,
    }
  } else if (detailInfo.type.includes('residence')) {
    res = {
      businessId: id,
      templateType: 'residence',
    }
  }
  if (detailInfo.type === 'region-community') {
    res = {
      businessId: id,
      templateType: 'region-community',
    }
  }

  return res
}

const detailRes = ref([])
const detailResSpecial = ref([])

let tempRes = []
let buildData

const initImageList = () => {
  const el = refs.value.$el
  const descItemContainer = el.querySelectorAll(
    '.el-descriptions-item__container'
  )
  descItemContainer.forEach((item) => {
    const imageList = item.querySelectorAll('.image-list')
    if (imageList?.length) {
      // console.log(item)
      item.classList.add('image-wrapper')
    }
    const titleList = item.querySelectorAll('.title-special')
    if (titleList?.length) {
      item.classList.add('title-wrapper')
    }
  })
}

const getResidenceList = async () => {
  try {
    const res = await getResidenceTree({
      regionId: props.detailInfo.info.regionId,
    })
    if (res.success) {
      return res.data
    }
    return []
  } catch (e) {
    Message.error(e)
    return []
  }
}

const findNodeById = (tree, targetId) => {
  // console.log(tree, targetId)
  // 遍历树中的每个节点
  for (let i = 0; i < tree.length; i++) {
    // 检查当前节点的ID是否为目标ID
    if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
      // 如果是的话，返回当前节点
      return tree[i]
    }

    // 如果当前节点有子节点，则递归在子节点中查找
    if (tree[i].children && tree[i].children.length > 0) {
      const foundNode = findNodeById(tree[i].children, targetId)
      // 如果在子节点中找到了，则返回找到的节点
      if (foundNode !== undefined) {
        return foundNode
      }
    }
  }

  // 如果在树中没有找到目标ID，则返回undefined
  return undefined
}

const getRegionInfo = (params) => {
  getRegionDetail(params)
    .then(async (res) => {
      if (res.success) {
        const { templateType } = params
        const { base, special } = getSpecialColumns(res.data, templateType)
        if (props.detailInfo.type === 'region-live') {
          let residenceList = []
          if (props.detailInfo.info.regionId) {
            residenceList = await getResidenceList()
          }
          base.map((item) => {
            if (item.question?.includes('选择小区')) {
              if (item.answer) {
                if (props.detailInfo.info.regionName) {
                  item.answer = props.detailInfo.info.regionName
                  return
                }
                const residenceIds = item.answer.split(',')
                const firstResidenceId = residenceIds[0]
                const node = findNodeById(residenceList, firstResidenceId)
                if (node) {
                  const communityNode = findNodeById(
                    residenceList,
                    node.parentCode
                  )
                  if (communityNode) {
                    const selectResidenceList = communityNode.children || []
                    item.answer = residenceIds
                      .map((id) => {
                        return (
                          selectResidenceList.find((res) => res.pkid === id)
                            ?.areaName || ''
                        )
                      })
                      .join(',')
                  }
                }
              }
            }
          })
          detailRes.value = base
        } else {
          if (props.detailInfo.type === 'region-community') {
            base.unshift({
              question: '1、社区名称',
              answer: props.detailInfo.info.name,
              remark: '',
              unit: null,
            })
          }
          detailRes.value = base
        }
        detailResSpecial.value = special
      } else {
        Message.error(res.message)
      }
    })
    .finally(() => {
      nextTick(() => {
        initImageList()
      })
    })
}

watch(
  () => props.detailInfo.id,
  (val) => {
    if (val) {
      activeName.value = 'detail'
      const parmas = getParamsById(val)
      if (props.detailInfo.type?.includes('region-')) {
        getRegionInfo(parmas)
        return
      }
      if (props.detailInfo.type?.includes('residence')) {
        queryByResidenceId(val).then((res) => {
          if (res.success) {
            console.log(res.data)
          }
        })
      }
      queryQuestion(parmas)
        .then((res) => {
          if (res.success) {
            const { templateType } = parmas
            if (templateType === 'community' || templateType === 'street') {
              const { base, special } = getSpecialColumns(
                res.data,
                templateType
              )
              detailRes.value = base
              detailResSpecial.value = special
            } else {
              detailRes.value = getColumns(res.data, true)
              detailResSpecial.value = []
              buildData = null
              if (templateType === 'residence') {
                tempRes = cloneDeep(detailRes.value)
              }
            }
          }
        })
        .finally(() => {
          nextTick(() => {
            initImageList()
          })
        })
    }
  }
)

// 点击建筑出现的特殊详情
const specialTypeList = ['building', 'history', 'update']
const specialTypeListNew = ['oldBuilding']
watch(
  () => props.detailInfo.type,
  (val) => {
    if (specialTypeList.includes(val)) {
      detailRes.value = []
      detailResSpecial.value = props.detailInfo.info
      colon.value = false
    } else if (specialTypeListNew.includes(val)) {
      detailRes.value = props.detailInfo.info
      detailResSpecial.value = []
      colon.value = false
      nextTick(() => {
        initImageList()
      })
    } else {
      colon.value = true
    }
  }
)

const statusInfo = computed(() => {
  if (props.detailInfo.type?.includes('region-') && props.detailInfo.info) {
    return getStatusInfo(props.detailInfo.info.status)
  }
  return getStatusInfo(props.status)
})

const getQuestion = (question) => {
  if (question.endsWith(':')) {
    if (!specialTypeList.includes(props.detailInfo.type)) {
      return question
    }
    return question.slice(0, -1)
  } else {
    if (specialTypeList.includes(props.detailInfo.type)) {
      return question
    }
    return question + ':'
  }
}

const getImageList = (string) => {
  if (string) {
    // console.log(imgUrl)
    return string.split(',').filter((x) => !!x)
  } else {
    return []
  }
}

const getBuildData = async () => {
  if (buildData) {
    return buildData
  }
  const res = await queryQuestion({
    businessId: props.detailInfo.id,
    templateType: 'build',
  })
  if (res.success) {
    buildData = getColumns(res.data, true, 'build')
  }
  return buildData
}

const activeName = ref('detail')

const handleClick = (tab) => {
  if (tab) {
    const { name } = tab
    if (name === 'build') {
      getBuildData().then((res) => {
        detailRes.value = res
        nextTick(() => {
          initImageList()
        })
      })
    } else {
      detailRes.value = tempRes
      nextTick(() => {
        initImageList()
      })
    }
  }
}

const handleShowResidence = (id) => {
  emitter.emit('tabDetail', {
    pkid: id,
    residenceId: id,
    type: '',
  })
}

const handleDetailClick = (item) => {
  let info
  if (props.detailInfo.type === 'update') {
    info = {
      relationId: item.id,
      pkid: item.id,
      name: item.name,
      status: 0,
      type: 'region-business',
    }
  } else if (props.detailInfo.type === 'history') {
    info = {
      relationId: item.id,
      pkid: item.id,
      name: item.name,
      status: 0,
      type: 'region-build',
    }
  } else {
    const { id } = item
    info = {
      pkid: id,
      residenceId: id,
      type: '',
    }
  }
  emitter.emit('tabDetail', info)
}

const handleApplyClick = () => {
  emits('applyRecord')
}

const editPopupShow = ref(false)
const editPkid = ref('')
const editBuildId = ref('')
const isPoint = computed(() => {
  const info = props.detailInfo?.info || []
  if (Array.isArray(info)) {
    return info.some((item) => item.question === '隐患信息')
  } else {
    return false
  }
})
const handleEditPopupClose = () => {
  editPopupShow.value = false
}

const handleUpdateData = () => {
  let bm
  let promise
  let buildId
  if (isPoint.value) {
    bm = editPkid.value
    promise = getPoint(bm)
  } else {
    buildId = editPkid.value
    bm = editBuildId.value
    promise = getBuildingInfo(buildId)
  }
  promise.then((res) => {
    if (res.success) {
      detailRes.value = getBuildDetail(
        res.data,
        bm,
        buildId,
        isPoint.value,
        user.roleLevel
      )
      nextTick(() => {
        initImageList()
      })
    }
  })
  editPopupShow.value = false
}

const handleShowEditPopup = () => {
  const id = props.detailInfo.info.find(
    (item) => item.question === '楼宇隐患信息' || item.question === '隐患信息'
  )?.id
  const bm = props.detailInfo.info.find(
    (item) => item.question === '楼宇核实'
  )?.id
  if (!id) {
    Message.error('未找到楼宇基础信息')
    return
  }
  editPkid.value = id
  editBuildId.value = bm
  editPopupShow.value = true
}

onMounted(() => {
  getArea()
})
</script>

<template>
  <div class="community-details">
    <div class="header">
      <div class="name__wrapper">
        <div class="left">
          <span class="title">详情</span>
          <span
            v-show="
              !specialTypeList.includes(detailInfo.type) &&
              !specialTypeListNew.includes(detailInfo.type)
            "
            class="status"
            :style="{ background: statusInfo.bgColor, color: statusInfo.color }"
            >{{ statusInfo.statusText }}</span
          >
        </div>
        <div class="right">
          <i @click="closeDialog" class="el-icon-close"></i>
        </div>
      </div>
    </div>

    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="详情信息" name="detail"></el-tab-pane>
      <el-tab-pane
        v-if="detailInfo.type.includes('residence')"
        label="楼宇信息"
        name="build"
      ></el-tab-pane>
    </el-tabs>
    <!--    已通过和待审核状态可以审核-->
    <el-button
      v-if="
        (status == 2 || status == -1) &&
        !specialTypeList.includes(detailInfo.type) &&
        currentUser?.hasPermission(PERMISSIONS.一张图审核)
      "
      class="right-button"
      type="text"
      @click="handleApplyClick"
    >
      {{ currentUser?.getButtonName(PERMISSIONS.一张图审核) }}
    </el-button>
    <el-button
      v-if="
        specialTypeListNew.includes(detailInfo.type) &&
        currentUser?.hasPermission(PERMISSIONS.一张图楼宇编辑)
      "
      class="right-button"
      type="text"
      @click="handleShowEditPopup"
    >
      {{ currentUser?.getButtonName(PERMISSIONS.一张图楼宇编辑) }}
    </el-button>
    <div
      :class="[
        'body base-info',
        specialTypeList.includes(detailInfo.type) ? 'show-label' : '',
      ]"
    >
      <el-descriptions :column="1" :border="false" ref="refs" :colon="colon">
        <el-descriptions-item
          v-for="(item, index) in detailRes"
          :label="item.question"
          :key="index"
        >
          <template slot="label" v-if="item.unit === '|special-title|'">
            <div class="title-special">
              <i class="el-icon"></i>
              <span>{{ item.question }}</span>
            </div>
          </template>
          <template v-if="item.unit === '|special-file|'">
            <div class="image-list">
              <el-image
                v-for="(val, idx) in getImageList(item.answer)"
                :key="idx"
                style="width: 100px; height: 100px"
                :src="val"
                fit="cover"
                :preview-src-list="getImageList(item.answer)"
              >
              </el-image>
            </div>
          </template>
          <template v-else-if="item.unit === '|special-title|'"> </template>
          <template v-else-if="item.unit === '|special-residence|'">
            <div class="content-residence">
              <span>{{ item.answer }}</span>
              <span
                class="detail"
                v-if="item.id"
                @click="handleShowResidence(item.id)"
                >详情&nbsp;></span
              >
            </div>
          </template>
          <template v-else>
            {{ item.answer }}{{ item.answer && item.unit ? item.unit : '' }}
          </template>
        </el-descriptions-item>
        <!--          <template v-else>-->
        <!--            <div class="list"></div>-->
        <!--          </template>-->
      </el-descriptions>
      <div class="group-info">
        <!--        <div-->
        <!--          class="group"-->
        <!--          v-for="(item, index) in detailResSpecial"-->
        <!--          :key="index"-->
        <!--        >-->
        <!--          <div class="group-title">{{ item.name }}</div>-->
        <!--          <div class="group-body">-->
        <!--            <el-card-->
        <!--              class="box-card"-->
        <!--              v-for="(val, idx) in item.children"-->
        <!--              :key="idx"-->
        <!--            >-->
        <!--              <el-descriptions-->
        <!--                title=""-->
        <!--                :colon="colon"-->
        <!--                :column="1"-->
        <!--                :border="false"-->
        <!--              >-->
        <!--                <el-descriptions-item-->
        <!--                  :label="getQuestion(v.question)"-->
        <!--                  v-for="(v, i) in val"-->
        <!--                  :key="i"-->
        <!--                >-->
        <!--                  {{ v.answer }}{{ v.answer && v.unit ? v.unit : '' }}-->
        <!--                </el-descriptions-item>-->
        <!--              </el-descriptions>-->
        <!--            </el-card>-->
        <!--          </div>-->
        <!--        </div>-->
        <div v-for="(item, index) in detailResSpecial" :key="index">
          <div class="title">
            <i class="el-icon"></i>
            <span class="text">{{ item.name }}</span>
            <span
              v-if="specialTypeList.includes(detailInfo.type)"
              class="detail"
              @click="handleDetailClick(item)"
              >详情&nbsp;></span
            >
          </div>
          <div class="content">
            <div
              class="building-info-item"
              v-for="(val, idx) in item.children"
              :key="idx"
            >
              <span v-for="(v, i) in val" :key="i">
                <template v-if="v.unit === '|special-file|'">
                  <div class="image-wrapper">
                    <div class="image-title">{{ getQuestion(v.question) }}</div>
                    <div class="image-list">
                      <el-image
                        v-for="(m, n) in getImageList(v.answer)"
                        :key="n"
                        style="width: 100px; height: 100px"
                        :src="m"
                        fit="cover"
                        :preview-src-list="getImageList(v.answer)"
                      >
                      </el-image>
                    </div>
                  </div>
                </template>
                <template v-else>
                  {{ getQuestion(v.question) }} {{ v.answer
                  }}{{ v.answer && v.unit ? v.unit : '' }}
                </template>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <build-edit-popup
      :visible="editPopupShow"
      :pkid="editPkid"
      :roleLevel="user.roleLevel"
      :isPoint="isPoint"
      :buildCode="editBuildId"
      :city-list="areaInfoList"
      @closeDialog="handleEditPopupClose"
      @updateData="handleUpdateData"
    ></build-edit-popup>
  </div>
</template>

<style scoped lang="scss">
.community-details {
  display: flex;
  flex-direction: column;

  width: 430px;
  min-height: 200px;
  position: absolute;
  left: 0;
  top: 0;
  background-color: white;
  box-shadow: 0 0 6px 0 rgba(0, 10, 19, 0.2);
  border-radius: 4px;
  overflow: hidden;
  z-index: 20;
  height: 100%;

  .header {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f3f3f9;
    padding-bottom: 10px;

    .name__wrapper {
      display: flex;
      align-items: center;

      width: 402px;
      height: 35px;
      margin-left: 11px;
      margin-top: 10px;
      justify-content: space-between;
      background-image: url('~@/assets/images/one-map/community-region-popup-name-background.png');
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }

    .left {
      margin-left: 21px;
      margin-top: -4px;
    }

    .right {
      line-height: 21px;

      .el-icon {
        &:hover {
          cursor: pointer;
        }
      }
    }

    span.title {
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      line-height: 14px;
      color: black;
    }

    .status {
      width: 54px;
      height: 22px;
      display: inline-block;
      margin-left: 212px;
      border-radius: 8px;
      font-size: 14px;
      line-height: 22px;
      text-align: center;
      //background-color: rgba(255,255,0,0.4);
    }
  }

  :deep(.el-tabs) {
    .el-tabs__nav-wrap {
      padding: 0 16px;
    }
  }
  .right-button {
    position: absolute;
    right: 0;
    top: 56px;
    width: 100px;
  }
  .body {
    height: calc(90% - 60px);
    display: flex;
    flex-direction: column;
    padding: 12px;
    overflow-y: auto;

    .group-info {
      .group-title {
        margin: 10px 0;
      }
    }

    :deep(.el-descriptions-item__label) {
      max-width: 60% !important;
    }

    &.show-label {
      :deep(.el-descriptions-item__label) {
        max-width: 100% !important;
      }
    }

    .title-special {
      margin-top: 5px;
      margin-bottom: 8px;
      display: flex;
      align-items: center;

      .el-icon {
        width: 3px;
        height: 18px;
        margin-right: 6px;
        background-color: #28b1e4;
        border-radius: 2px;
      }

      span {
        font-size: 14px;
        font-weight: bold;
      }
    }

    .content-residence {
      height: 21px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .detail {
        color: #28b1e4;
        font-size: 14px;
        font-weight: bold;
        cursor: pointer;
      }
    }
    :deep(.title-wrapper) {
      .el-descriptions-item__label {
        max-width: 100% !important;
        &:after {
          content: '';
        }
      }
    }
  }

  :deep(.el-descriptions-item__label) {
    //display: inline-block;
    //width: 262px !important;
    color: #717689;
  }

  .base-info {
    //display: flex;
    //flex-direction: column;
    //justify-content: center;
    //margin-bottom: 10px;
    span {
      font-size: 14px;
      line-height: 32px;
    }
    :deep(.el-descriptions-item__cell) {
      padding-top: 6px;
      padding-bottom: 6px !important;
      border-bottom: 1px dashed #e1e1eb !important;
      .el-descriptions-item__content {
        color: #27475f !important;
      }
    }

    :deep(.image-wrapper) {
      width: 100%;
      display: flex;
      flex-direction: column;

      .image-title {
        word-wrap: break-word;
      }

      .image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
      }
    }
  }

  .group-info {
    .content {
      padding-left: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      span {
        font-size: 14px;
        line-height: 32px;
      }
    }

    .title {
      margin-top: 5px;
      margin-bottom: 8px;
      display: flex;
      align-items: center;

      :deep(.el-icon) {
        width: 3px;
        height: 18px;
        margin-right: 6px;
        background-color: #28b1e4;
        border-radius: 2px;
      }

      .detail {
        color: #28b1e4;
        font-size: 14px;
        font-weight: bold;
        cursor: pointer;
      }

      .text {
        width: calc(100% - 60px);
        // 溢出打点
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      span {
        font-size: 14px;
        font-weight: bold;
      }
    }

    .building-info-item {
      display: flex;
      flex-direction: column;
      padding: 11px 15px;
      background-color: rgba(249, 249, 252, 1);
      border-radius: 4px;
      margin-bottom: 12px;

      color: #717689;

      .position {
        color: RGBA(39, 71, 95, 1);
      }
    }
  }
}
</style>
